package com.ghline.caloncabe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import vn.clevernet.android.sdk.ClevernetView;
import vn.clevernet.android.sdk.ClevernetView.ClevernetViewCallbackListener;
import vn.sunnet.util.ads.QplayAdView;
import vn.sunnet.util.ads.QplayAdView.WidgetSize;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.atools.MyScheRcv;
import com.example.atools.Tools;
import com.example.util.AdsClass;
import com.example.util.GameDialogExit;
import com.anhthao.nuotcabe.R;
import com.ghline.caloncabe.manager.SoundManager;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements SensorEventListener {

	private static final String TAG = MainActivity.class.getSimpleName();
	private GameView gameView;
	private RelativeLayout lnAdSunNet;
	private QplayAdView adView;
	private RelativeLayout.LayoutParams lp;

	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	public SharedPreferences sp;
	public Editor editor;
	public static MediaPlayer player;
	CountDownTimer timer;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Quan trong dat cao dau on create
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		// Bo title cua man hinh
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Tao man hinh full screen
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		setContentView(R.layout.main);

		gameView = new GameView(this);

		lnAdSunNet = new RelativeLayout(this);
		adView = new QplayAdView(this);

		lp = new RelativeLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
		lnAdSunNet.setGravity(80);
		lnAdSunNet.addView(gameView);
		//addContentView(lnAdSunNet, new ViewGroup.LayoutParams(-1, -1));
		setContentView(lnAdSunNet);

		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		mAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_GAME);

		sp = PreferenceManager.getDefaultSharedPreferences(this);
		editor = sp.edit();

		if (player == null) {
			player = new MediaPlayer();
		}

		try {
			player = MediaPlayer.create(this, R.raw.music);
			player.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		timer = new CountDownTimer(0, 0) {
			@Override
			public void onTick(long millisUntilFinished) {

			}

			@Override
			public void onFinish() {
				player.setLooping(true);
				player.setVolume(0.6f, 0.6f);
				if (sp.getBoolean(GameView.KEY_MUSIC, true) == true) {
					player.start();
				}
			}
		};
		timer.start();

		/**
		 * Cai notification
		 */
		
		loadConfig();
	}

	private void loadConfig() {
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		MyScheRcv.loadConfig(getBaseContext());
		MyScheRcv.sendReqClientUpdate(this);
		// Thiết lập alarm
		Tools.setAlarm(getBaseContext());

		addAds();
		
	}

	public void addAds() {
		final String __h = "0";
		final String __v = "0";
		AdsClass ac = new AdsClass(this, lnAdSunNet, __h, __v);
	}
	
	private RelativeLayout createLayout(View obj, String __h, String __v) {
		// Dung cho quang cao khong co layout
		//RelativeLayout lnAd = new RelativeLayout(activity);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		
		
		
		
		
		if(__h.equals("1")){
			lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		}else{
			lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		}
		if(__v.equals("0")){
			lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
		}else if(__v.equals("1")){
			lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		}else{
			lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		}
		//lnAd.addView(obj, lp);// adView=quang cao cua minh
		//activity.addContentView(lnAd, new ViewGroup.LayoutParams(-1, -1));
		
		lnAdSunNet.addView(obj, lp);
		return lnAdSunNet;
	}
	private void addSunetAds(String __h, String __v) {
		QplayAdView adView2 = new QplayAdView(this);
		createLayout(adView2, __h, __v);
		if (adView2 != null) {
			adView2.loadAd(WidgetSize.SMALL);
		}
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	private boolean isexit = false;

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		int l1 = gameView.getBtPlay().getX();
		int w1 = gameView.getBtPlay().getWidth();
		int t1 = gameView.getBtPlay().getY();
		int h1 = gameView.getBtPlay().getHeight();

		int l2 = gameView.getBtExit().getX();
		int w2 = gameView.getBtExit().getWidth();
		int t2 = gameView.getBtExit().getY();
		int h2 = gameView.getBtExit().getHeight();

		int numLevel = sp.getInt(GameView.KEY_NUMBER_LEVEL, 0);

		if (gameView.getGameThread().currentState == GameThread.STATE_SHOW_MENU) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				gameView.getBtMusicMain().handleActionDown((int) event.getX(),
						(int) event.getY());
				gameView.getBtSoundMain().handleActionDown((int) event.getX(),
						(int) event.getY());
				gameView.getBtHelp().handleActionDown((int) event.getX(),
						(int) event.getY());
				if ((event.getX() >= l2) && (event.getX() <= (l2 + w2))) {
					if ((event.getY() >= t2) && (event.getY() <= (t2 + h2))) {
						isexit = true;
						editor.putInt(GameView.KEY_NUMBER_LEVEL,
								gameView.getNumLevelCompleted());
						editor.commit();

						GameDialogExit gde = new GameDialogExit(
								MainActivity.this);
						gde.show();

						return true;
					}
				}
			}

			if (event.getAction() == MotionEvent.ACTION_UP) {
				if ((event.getX() >= l1) && (event.getX() <= (l1 + w1))) {
					if ((event.getY() >= t1) && (event.getY() <= (t1 + h1))) {
						for (int i = 0; i <= numLevel; i++) {
							gameView.getLevelSelectSprite()[i]
									.setLevelSelcetBitmap(gameView
											.getLevelOpenBitmap());
							gameView.getLevelSelectSprite()[i].setUnlock(true);
						}
						gameView.getGameThread().setState(
								GameThread.STATE_SHOW_LEVEL);
						if (player != null && player.isPlaying()) {
							player.pause();
						}
						return true;
					}
				}

				if (gameView.getBtMusicMain().isTouched()) {
					gameView.setMusicOn(sp.getBoolean(GameView.KEY_MUSIC, true));
					if (gameView.isMusicOn() == true) {
						gameView.setMusicOn(false);
						editor.putBoolean(GameView.KEY_MUSIC, false);
						editor.commit();
						if (player != null && player.isPlaying()) {
							player.pause();
						}
					} else {
						gameView.setMusicOn(true);
						editor.putBoolean(GameView.KEY_MUSIC, true);
						editor.commit();
						if (player != null) {
							player.seekTo(0);
							player.start();
						}
					}
				}

				if (gameView.getBtSoundMain().isTouched()) {
					gameView.setSoundOn(sp.getBoolean(GameView.KEY_SOUND, true));
					if (gameView.isSoundOn() == true) {
						gameView.setSoundOn(false);
						editor.putBoolean(GameView.KEY_SOUND, false);
						editor.commit();
					} else {
						gameView.setSoundOn(true);
						editor.putBoolean(GameView.KEY_SOUND, true);
						editor.commit();
					}
				}
				if (!isexit && gameView.getBtHelp().isTouched()) {
					gameView.getGameThread().setState(GameThread.STATE_HELP);
					return true;
				}
				return true;
			}
		}
		return false;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			int x = (int) event.values[0];
			int y = (int) event.values[1];
			int z = (int) event.values[2];
			gameView.setaX(x);
			gameView.setaY(y);
			gameView.setaZ(z);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_GAME);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mSensorManager.unregisterListener(this);
		if (player != null && player.isPlaying()) {
			player.stop();
			player.release();
		}
	}

	@Override
	protected void onStop() {
		Log.d(TAG, "Stopping....");
		super.onStop();
		SoundManager.cleanup();
		finish();
	}

	@Override
	protected void onDestroy() {
		// removeAds();
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
}
